package com.ruibang.glass.sale.service.impl;


import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.common.domain.DictInfo;
import com.ruibang.glass.common.domain.ProductInfo;
import com.ruibang.glass.common.domain.camunda.BpmProcessInstanceCreate;
import com.ruibang.glass.common.domain.camunda.BpmProcessInstanceStatus;
import com.ruibang.glass.common.domain.file.FileBusiness;
import com.ruibang.glass.common.domain.material.MaterialCpBcpItemsInfo;
import com.ruibang.glass.common.domain.material.MaterialProductsOut;
import com.ruibang.glass.common.domain.sale.SaleContractManagement;
import com.ruibang.glass.common.utils.ApproveUserNameUtils;
import com.ruibang.glass.frequencycontrol.annotation.RedissonLock;
import com.ruibang.glass.sale.constant.Constants;
import com.ruibang.glass.sale.constant.SaleErrorCode;
import com.ruibang.glass.sale.constant.SaleMenuIdCode;
import com.ruibang.glass.sale.domain.req.GSaleContractManReq;
import com.ruibang.glass.sale.domain.req.GSaleStatisticsManReq;
import com.ruibang.glass.sale.domain.req.SalePayProgressReq;
import com.ruibang.glass.sale.domain.req.SaleshippingApplicationReq;
import com.ruibang.glass.sale.dto.*;
import com.ruibang.glass.sale.entity.*;
import com.ruibang.glass.sale.feign.CamundaApi;
import com.ruibang.glass.sale.feign.FileApi;
import com.ruibang.glass.sale.feign.MaterialApi;
import com.ruibang.glass.sale.feign.PortalApi;
import com.ruibang.glass.sale.mapper.*;
import com.ruibang.glass.sale.service.*;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.common.constant.CommonConstant;
import com.teaming.cloud.framework2.common.exception.ServiceException;
import com.teaming.cloud.framework2.common.model.ResultBody;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.ruibang.glass.common.constants.RedisKey.MATERIAL_IN_WAREHOUSE_NUMBER;
import static com.ruibang.glass.common.constants.RedisKey.MATERIAL_SHPPING_WAREHOUSE_NUMBER;

/**
 * <p>
 * 发货申请记录表 服务实现类
 * </p>
 *
 * @author mameng
 * @since 2024-03-30
 */
@Service
public class GSaleShippingApplicationServiceImpl extends ServiceImpl<SaleShippingApplicationMapper, SaleShippingApplication> implements SaleShippingApplicationService {

    @Autowired
    private CommonService commonService;

    @Autowired
    private CamundaApi camundaApi;


    @Autowired
    private RedisSingleService rediservice;

    @Autowired
    private FileApi fileApi;

    private static final String MENU_ID = "e0235deec6a011a6f2b5840cea091013";

    @Autowired
    private SalesShippingItemsService salesShippingItemsService;

    @Autowired
    private GSaleReturnExchangeOrderDetailMapper gSaleReturnExchangeOrderDetailMapper;

    @Autowired
    private GSaleReturnExchangeOrderMapper saleReturnExchangeOrderMapper;

    @Autowired
    private GSaleOrderMapper saleOrderMapper;


    private static final String finishName = "审批人";

    @Autowired
    private PortalApi portalApi;


    @Autowired
    private MaterialApi materialApi;

    @Autowired
    private GSaleCustomerManagementMapper saleCustomerManagementMapper;

    @Autowired
    private GSaleContractManagementMapper saleContractManagementMapper;

    private static final String SALE_OUT_NUMBER = "sale_out_number";

    private static final String SALE_OR_NUMBER = "sale_or_number";

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Override
    public IPage<SaleShippingApplication> getPage(SaleshippingApplicationReq saleshippingApplicationReq) {
        LambdaQueryWrapper<SaleShippingApplication> queryWrapper = Wrappers.<SaleShippingApplication>lambdaQuery();
        if (StringUtils.isNotBlank(saleshippingApplicationReq.getContractName())) {
            queryWrapper.like(SaleShippingApplication::getContractName, saleshippingApplicationReq.getContractName());
        }
        if (StringUtils.isNotBlank(saleshippingApplicationReq.getOrderNumber())) {
            queryWrapper.like(SaleShippingApplication::getOrderNumber, saleshippingApplicationReq.getOrderNumber());
        }
        if (StringUtils.isNotBlank(saleshippingApplicationReq.getShippingProgress())) {
            queryWrapper.like(SaleShippingApplication::getShippingProgress, saleshippingApplicationReq.getShippingProgress());
        }
        if (saleshippingApplicationReq.getOrderStartTime() != null) {
            queryWrapper.ge(SaleShippingApplication::getOrderTime, saleshippingApplicationReq.getOrderStartTime());
        }
        if (saleshippingApplicationReq.getOrderEndTime() != null) {
            queryWrapper.le(SaleShippingApplication::getOrderTime, saleshippingApplicationReq.getOrderEndTime());
        }
        if (saleshippingApplicationReq.getShippingStartDate() != null) {
            queryWrapper.ge(SaleShippingApplication::getShippingDate, saleshippingApplicationReq.getShippingStartDate());
        }
        if (saleshippingApplicationReq.getShippingEndDate() != null) {
            queryWrapper.le(SaleShippingApplication::getShippingDate, saleshippingApplicationReq.getShippingEndDate());
        }
        Page<SaleShippingApplication> saleShippingApplicationPage = baseMapper.selectPage(new Page<>(saleshippingApplicationReq.getPageNo(), saleshippingApplicationReq.getPageSize()),
                queryWrapper.orderByDesc(SaleShippingApplication::getUpdateTime)
        );
        Map<Object, Object> userMap = rediservice.hmget(RedisKey.USER_GROUP_TYPE);
        List<String> businessKeys = saleShippingApplicationPage.getRecords().stream().map(SaleShippingApplication::getId).collect(Collectors.toList());
        Map<String, BpmProcessInstanceStatus> processMap = null;
        //获取业务流程状态
        ResultBody<List<BpmProcessInstanceStatus>> resultBody = camundaApi.queryProcessInstanceStatus(businessKeys);
        if (resultBody != null && CollectionUtils.isNotEmpty(resultBody.getData())) {
            processMap = resultBody.getData().stream().collect(Collectors.toMap(bp -> bp.getBusinessKey(), bp -> bp, (bp1, bp2) -> bp1));
        }
        if (processMap != null) {
            for (SaleShippingApplication saleShippingApplication : saleShippingApplicationPage.getRecords()) {
                if (processMap.get(saleShippingApplication.getId()) != null) {
                    saleShippingApplication.setStatus(String.valueOf(processMap.get(saleShippingApplication.getId()).getStatus()));
                    saleShippingApplication.setProcessId(processMap.get(saleShippingApplication.getId()).getProcessInstanceId());
//                    saleShippingApplication.setApproveStatus(processMap.get(saleShippingApplication.getId()).getResult());
                    saleShippingApplication.setNodeName(processMap.get(saleShippingApplication.getId()).getNodeName());
                    String userId = processMap.get(saleShippingApplication.getId()).getUserId();
                    if (StringUtils.isNotBlank(userId) && !StringUtils.equals(userId, "null")) {
                        String approveName = ApproveUserNameUtils.getApproveName(userId, userMap);
                        saleShippingApplication.setApproveUser(approveName);
                        saleShippingApplication.setApproveUserId(userId);
                    }
                }
            }
        }
        return saleShippingApplicationPage;
    }

    @Override
    public IPage<GSaleShappingDTO> getNewPage(GSaleContractManReq gSaleContractManReq) {
        IPage<GSaleShappingDTO> newPage = baseMapper.getNewPage(new Page<GSaleContractManagementDTO>(gSaleContractManReq.getPageNo(), gSaleContractManReq.getPageSize()), gSaleContractManReq);
        if (newPage.getRecords() != null) {
            List<String> collect = newPage.getRecords().stream().map(GSaleShappingDTO::getOrderId).collect(Collectors.toList());
            List<GSaleShappingDTO> sumAmountByNumber = baseMapper.getSumAmountByNumber(collect);
            for (GSaleShappingDTO saleShappingDTO : newPage.getRecords()) {
                if (StringUtils.isNotEmpty(saleShappingDTO.getOrderingSettlementCustomer())) {
                    GSaleCustomerManagement saleCustomerManagement = saleCustomerManagementMapper.selectById(saleShappingDTO.getOrderingSettlementCustomer());
                    if (saleCustomerManagement != null) {
                        saleShappingDTO.setOrderingSettlementCustomer(saleCustomerManagement.getCustomerName());
                    }
                    GSaleCustomerManagement saleCustomerManagement1 = saleCustomerManagementMapper.selectById(saleShappingDTO.getDemandCustomer());
                    if (saleCustomerManagement1 != null) {
                        saleShappingDTO.setDemandCustomer(saleCustomerManagement1.getCustomerName());
                    }
                }
                for (GSaleShappingDTO saleShappingDTO1 : sumAmountByNumber) {
                    if (StringUtils.equals(saleShappingDTO.getOrderNumber(), saleShappingDTO1.getOrderNumber())) {
                        saleShappingDTO.setReturnAmountCount(saleShappingDTO1.getReturnAmountCount());
                        saleShappingDTO.setReturnAllQuality(saleShappingDTO1.getReturnAllQuality());
                        if (saleShappingDTO1.getReturnAmountCount() != null && saleShappingDTO1.getTotalAmount() != null) {
                            BigDecimal subtract = saleShappingDTO1.getTotalAmount().subtract(saleShappingDTO1.getReturnAmountCount());
                            saleShappingDTO1.setTrueAllQuality(subtract);
                        }
                        if (saleShappingDTO1.getTotalAmount() != null && saleShappingDTO1.getReturnAllQuality() != null) {
                            BigDecimal subtract = saleShappingDTO1.getTotalAmount().subtract(saleShappingDTO1.getReturnAllQuality());
                            saleShappingDTO1.setReturnAmountCount(subtract);
                        }

                    }
                }
            }
        }
        return newPage;
    }

    @Override
    public void orderExport(GSaleContractManReq gSaleOrderReq, HttpServletResponse response) {
        String fileName = "销售出入库报表" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + ".xlsx";
        try {
            // 对文件名进行URL编码
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");

            // 设置响应内容类型和字符编码
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");

            // 设置Content-Disposition头部，告诉浏览器这是一个文件下载请求
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);

            // 获取导出数据
            IPage<GSaleShappingDTO> checkList = baseMapper.getNewPage(new Page<GSaleContractManagementDTO>(0, 2000L), gSaleOrderReq);
            List<GSaleShappingDTO> list = checkList.getRecords();

            // 使用EasyExcel写入数据到响应输出流
            EasyExcel.write(response.getOutputStream(), GSaleContractManagementDTO.class).excelType(ExcelTypeEnum.XLSX).sheet("销售订单报表").doWrite(list);

            // 刷新输出流
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常，例如设置错误状态码或错误消息
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出Excel时发生错误");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    @Override
    public IPage<SaleShippingApplication> moreList(SaleshippingApplicationReq saleshippingApplicationReq) {
        IPage<SaleShippingApplication> saleShippingApplicationIPage = baseMapper.moreList(new Page<SaleShippingApplication>(saleshippingApplicationReq.getPageNo(), saleshippingApplicationReq.getPageSize()),
                saleshippingApplicationReq);
        for (SaleShippingApplication saleShippingApplication : saleShippingApplicationIPage.getRecords()) {
            if (saleShippingApplication.getPlanQuantity()!=null && saleShippingApplication.getTotalQuantity()!=null){
                saleShippingApplication.setMoreQuality(saleShippingApplication.getPlanQuantity().subtract(saleShippingApplication.getTotalQuantity()));
            }
        }
        return saleShippingApplicationIPage;
    }

    @Override
    public List<SaleShippingApplication> getMoreSelectList() {
        return baseMapper.getMoreSelectList();
    }

    /**
     * 新增发货申请
     *
     * @param saleShippingApplicationList
     */
    @Override
    public void addSaleShippingApplication(List<SaleShippingApplication> saleShippingApplicationList) {
        List<SaleShippingApplication> execute = transactionTemplate.execute(tran -> {
            for (SaleShippingApplication saleShippingApplication : saleShippingApplicationList) {
                //数据来源于退换货
                if (StringUtils.isNotEmpty(saleShippingApplication.getId())) {
                    saleShippingApplication.setReturnId(saleShippingApplication.getId());
                    GSaleReturnExchangeOrder gSaleReturnExchangeOrder = saleReturnExchangeOrderMapper.selectById(saleShippingApplication.getId());
                    gSaleReturnExchangeOrder.setIsStatus(Constants.TWO_STR);
                    saleReturnExchangeOrderMapper.updateById(gSaleReturnExchangeOrder);
                }
                /**
                 * 数据来源于退换货  并且更新换货状态
                 */
                if (CollectionUtils.isNotEmpty(saleShippingApplication.getSalesShippingItemsList())) {
                    for (SalesShippingItems salesShippingItems : saleShippingApplication.getSalesShippingItemsList()) {
                        if (salesShippingItems.getQuantity() == null) {
                            throw new ServiceException(SaleErrorCode.RETURN_CHANGE_PRODUCT_NULL.getCode(), SaleErrorCode.RETURN_CHANGE_PRODUCT_NULL.getMsg());
                        }
                        if (StringUtils.isNotEmpty(salesShippingItems.getId())) {
                            GSaleReturnExchangeOrderDetail gSaleReturnExchangeOrderDetail = gSaleReturnExchangeOrderDetailMapper.selectById(salesShippingItems.getId());
                            ResultBody<ProductInfo> productById = portalApi.getProductById(gSaleReturnExchangeOrderDetail.getProductId());
                            saleShippingApplication.setProductId(productById.getData().getProductId());
                            saleShippingApplication.setProductName(productById.getData().getProductName());
                            saleShippingApplication.setSpecification(salesShippingItems.getSpecification());
                            saleShippingApplication.setExecutionStandard(productById.getData().getStandard());
                        }
                        saleShippingApplication.setId("");
                        GSaleOrderManagement gSaleOrderManagement = saleOrderMapper.selectById(salesShippingItems.getOrderId());
                        saleShippingApplication.setOrderNumber(gSaleOrderManagement.getOrderNumber());
                        saleShippingApplication.setContractName(gSaleOrderManagement.getContractName());
                        saleShippingApplication.setContractNumber(gSaleOrderManagement.getContractNumber());
                        saleShippingApplication.setOrderTime(gSaleOrderManagement.getCreateTime());
                        saleShippingApplication.setShippingDate(gSaleOrderManagement.getDeliveryDate());
                        saleShippingApplication.setDeliveryOrderNumber(getMaterialShppingNumber());
                        saleShippingApplication.setOutboundNumber(getMaterialOUTNumber());
                        saleShippingApplication.setLogisticsNumber(StringDGGeneratorService.generateString());
                        if (saleShippingApplication.getReturnType().equals(Constants.ONE_STR)) {
                            saleShippingApplication.setReturnedQuantity(salesShippingItems.getQuantity());
                            saleShippingApplication.setShippedQuantity(BigDecimal.ZERO);

                        }
                        if (saleShippingApplication.getReturnType().equals(Constants.TWO_STR)) {
                            saleShippingApplication.setExchangedQuantity(salesShippingItems.getQuantity());
                            saleShippingApplication.setReturnedQuantity(BigDecimal.ZERO);
                        }
                        saleShippingApplication.setPendingShipment(salesShippingItems.getQuantity());
                        saleShippingApplication.setTotalQuantity(salesShippingItems.getQuantity());
                        saleShippingApplication.setPendingShipment(salesShippingItems.getQuantity());
                        saleShippingApplication.setCancelledQuantity(BigDecimal.ZERO);
                        saleShippingApplication.setApproveStatus(Constants.ZERO_STR);
                    }
                    baseMapper.insert(saleShippingApplication);
                } else {
                    baseMapper.insert(saleShippingApplication);
                }
            }
            return saleShippingApplicationList;
        });
        if (CollectionUtils.isNotEmpty(execute)) {
            for (SaleShippingApplication saleShippingApplication : saleShippingApplicationList) {
                BpmProcessInstanceCreate instanceCreate = new BpmProcessInstanceCreate();
                instanceCreate.setBusinessKey(saleShippingApplication.getId());
                instanceCreate.setMenuId(MENU_ID);
                //发起流程
                if (StringUtils.isNotBlank(saleShippingApplication.getCreateUserId())) {
                    Map<String, Object> variables = new HashMap<>();
                    variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_STARTER_USER_ID, saleShippingApplication.getCreateUserId());
                    variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_BUSINESS_KEY, saleShippingApplication.getId());
                    variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_MENU_ID, MENU_ID);
                    instanceCreate.setVariables(variables);
                }
                commonService.startProcess(instanceCreate);
            }
        }
    }


    @Override
    public void addLessShipping(SaleShippingApplication saleShippingApplication) {
        SaleShippingApplication execute = transactionTemplate.execute(tran -> {
            SaleShippingApplication saleShippingApplicationNew = baseMapper.selectById(saleShippingApplication.getId());
            saleShippingApplicationNew.setShappingStatus(Constants.TWO_STR);
            baseMapper.updateById(saleShippingApplicationNew);
            BigDecimal subtract = saleShippingApplicationNew.getTotalQuantity().subtract(saleShippingApplicationNew.getShippedQuantity());
            SaleShippingApplication saleShippingApplication1 = new SaleShippingApplication();
            saleShippingApplication1.setId("");
            saleShippingApplication1.setOrderNumber(saleShippingApplicationNew.getOrderNumber());
            saleShippingApplication1.setApprovalStatus(com.ruibang.glass.common.constants.Constants.ZERO_STR);
            saleShippingApplication1.setContractName(saleShippingApplicationNew.getContractName());
            saleShippingApplication1.setContractNumber(saleShippingApplicationNew.getContractNumber());
            saleShippingApplication1.setSpecification(saleShippingApplicationNew.getSpecification());
            saleShippingApplication1.setProductType(saleShippingApplicationNew.getProductType());
            saleShippingApplication1.setDeliveryOrderNumber(getMaterialShppingNumber());
            saleShippingApplication1.setOutboundNumber(getMaterialOUTNumber());
            saleShippingApplication1.setLogisticsNumber(StringDGGeneratorService.generateString());
            saleShippingApplication1.setOrderId(saleShippingApplicationNew.getId());
            saleShippingApplication1.setProductName(saleShippingApplicationNew.getProductName());
            saleShippingApplication1.setProductId(saleShippingApplicationNew.getProductId());
            saleShippingApplication1.setShippingDate(saleShippingApplicationNew.getShippingDate());
            saleShippingApplication1.setExecutionStandard(saleShippingApplicationNew.getExecutionStandard());
            saleShippingApplication1.setOrderingSettlementCustomer(saleShippingApplicationNew.getConsignorSettlementCustomer());
            saleShippingApplication1.setOrderTime(saleShippingApplicationNew.getOrderTime());
            saleShippingApplication1.setDemandCustomer(saleShippingApplicationNew.getDemandCustomer());
            saleShippingApplication1.setCreateUserId(saleShippingApplicationNew.getCreateUserId());
            saleShippingApplication1.setGrade(saleShippingApplicationNew.getGrade());
            saleShippingApplication1.setUpdateTime(LocalDateTime.now());
            saleShippingApplication1.setTotalQuantity(subtract);
            saleShippingApplication1.setPendingShipment(subtract);
            saleShippingApplication1.setCancelledQuantity(BigDecimal.ZERO);
            saleShippingApplication1.setReturnedQuantity(BigDecimal.ZERO);
            saleShippingApplication1.setShippedQuantity(BigDecimal.ZERO);
            saleShippingApplication1.setCompletionRate(BigDecimal.ZERO);
            saleShippingApplication1.setExchangedQuantity(BigDecimal.ZERO);
            saleShippingApplication1.setGrossUnitPrice(saleShippingApplicationNew.getGrossUnitPrice());
            saleShippingApplication1.setGrossAmount(saleShippingApplicationNew.getGrossAmount());
            saleShippingApplication1.setNetUnitPrice(saleShippingApplicationNew.getNetUnitPrice());
            saleShippingApplication1.setNetAmount(saleShippingApplicationNew.getNetAmount());
            saleShippingApplication1.setOtherMarkup(saleShippingApplicationNew.getOtherMarkup());
            saleShippingApplication1.setBulkDiscountPrice(saleShippingApplicationNew.getBulkDiscountPrice());
            saleShippingApplication1.setTransportAmount(saleShippingApplicationNew.getTransportAmount());
            saleShippingApplication1.setTotalAmount(saleShippingApplicationNew.getTotalAmount());
            saleShippingApplication1.setNetTotalAmount(saleShippingApplicationNew.getNetTotalAmount());
            saleShippingApplication1.setTaxAmount(saleShippingApplicationNew.getTaxAmount());
            saleShippingApplication1.setCreateTime(LocalDateTime.now());
            baseMapper.insert(saleShippingApplication1);
            return saleShippingApplication1;
        });
        if (execute != null) {
            BpmProcessInstanceCreate instanceCreate = new BpmProcessInstanceCreate();
            instanceCreate.setBusinessKey(execute.getId());
            instanceCreate.setMenuId(saleShippingApplication.getMenuId());
            //发起流程
            if (StringUtils.isNotBlank(execute.getCreateUserId())) {
                Map<String, Object> variables = new HashMap<>();
                variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_STARTER_USER_ID, execute.getCreateUserId());
                variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_BUSINESS_KEY, execute.getId());
                variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_MENU_ID, saleShippingApplication.getMenuId());
                instanceCreate.setVariables(variables);
            }
            commonService.startProcess(instanceCreate);
        }


    }


    @RedissonLock(key = MATERIAL_SHPPING_WAREHOUSE_NUMBER, prefixKey = "lock_")
    public String getMaterialShppingNumber() {
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern(CommonConstant.DATE_FORMAT_UN_SEPARATE));
        date = "M".concat(date);
        String code = "";

        Serializable number = rediservice.get(RedisKey.MATERIAL_SHPPING_WAREHOUSE_NUMBER);
        if (number == null || StringUtils.isBlank(number.toString())) {
            ResultBody<String> resultBody = portalApi.getValueByCode(SALE_OUT_NUMBER);
            if (resultBody != null && StringUtils.isNotBlank(resultBody.getData())) {
                number = resultBody.getData();
            }
        }
        if (number != null && StringUtils.isNotBlank(number.toString()) && number.toString().length() > 9) {
            String sequenceStr = number.toString().substring(9);
            int sequenceInt = Integer.parseInt(sequenceStr);
            sequenceInt = sequenceInt + 1;
            String newSequence = String.valueOf(sequenceInt);
            if (newSequence.length() == CommonConstant.FIVE_INT) {
                code = date.concat("0001");
            } else {
                code = date.concat(String.format("%04d", sequenceInt)); // 格式化数字为4位，不足部分用0填充
            }
        } else {
            code = date.concat("0001");
        }
        rediservice.set(RedisKey.MATERIAL_SHPPING_WAREHOUSE_NUMBER, code);
        DictInfo info = new DictInfo();
        info.setCsdm(RedisKey.MATERIAL_SHPPING_WAREHOUSE_NUMBER);
        info.setCsmc(code);
        portalApi.updateValueByCode(info);
        return code;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSaleShippingApplication(SaleShippingApplication saleShippingApplication) {
        SaleShippingApplication saleShippingApplication2 = baseMapper.selectById(saleShippingApplication.getId());
        if (saleShippingApplication2.getPlanQuantity() != null && StringUtils.isNotEmpty(saleShippingApplication.getOrderingSettlementCustomer()) && StringUtils.isEmpty(saleShippingApplication2.getDriverAndPhoneNumber())) {
            if (CollectionUtils.isEmpty(saleShippingApplication.getSalesShippingItemsList())) {
                throw new ServiceException(SaleErrorCode.SHIPPING_NO_ITEM.getCode(), SaleErrorCode.SHIPPING_NO_ITEM.getMsg());
            }
        }
        baseMapper.updateById(saleShippingApplication);
        fileApi.deleteByBusinessId(saleShippingApplication.getId());
        if (CollectionUtils.isNotEmpty(saleShippingApplication.getSalesShippingItemsList())) {
            for (SalesShippingItems salesShippingItems : saleShippingApplication.getSalesShippingItemsList()) {
                if (StringUtils.isEmpty(salesShippingItems.getShippingId())) {
                    salesShippingItems.setShippingId(saleShippingApplication.getId());
                    if (StringUtils.isEmpty(salesShippingItems.getLevelRack())) {
                        throw new ServiceException(SaleErrorCode.SHIPPING_NULL_ATYPE.getCode(), SaleErrorCode.SHIPPING_NULL_ATYPE.getMsg());
                    }
                    salesShippingItemsService.save(salesShippingItems);
                    baseMapper.updateByLevelRack(salesShippingItems.getQuantity(), salesShippingItems.getLevelRack());
                }
            }
        }
        if (CollectionUtils.isNotEmpty(saleShippingApplication.getCoaFileList())) {
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setFileIds(saleShippingApplication.getCoaFileList());
            fileBusiness.setBusinessId(saleShippingApplication.getId());
            fileApi.updateBusinessById(fileBusiness);
        }

        //当有coa报告和产品列表式 生成成品半成品出库单
        if (StringUtils.isNotEmpty(saleShippingApplication.getDeliveryAddress()) && StringUtils.isNotEmpty(saleShippingApplication.getDriverAndPhoneNumber())) {
            BigDecimal totalQuality = BigDecimal.ZERO;
            Map<Object, Object> userMap = rediservice.hmget(RedisKey.USER_GROUP_TYPE);
            SaleShippingApplication saleShippingApplication1 = baseMapper.selectById(saleShippingApplication.getId());
            MaterialProductsOut materialProductsOut = new MaterialProductsOut();
            materialProductsOut.setPreparer((String) userMap.get(saleShippingApplication.getCreateUserId()));
            materialProductsOut.setPreparerId(saleShippingApplication.getCreateUserId());
            materialProductsOut.setOutStorageOrderNo(saleShippingApplication1.getOutboundNumber());
            materialProductsOut.setCreationTime(LocalDateTime.now());
            if (StringUtils.isNotEmpty(saleShippingApplication.getContractNumber())) {
                GSaleContractManagement gSaleContractManagement = saleContractManagementMapper.selectOne(Wrappers.<GSaleContractManagement>lambdaQuery().eq(GSaleContractManagement::getNumber, saleShippingApplication.getContractNumber())
                        .last("limit 1"));
                materialProductsOut.setContractId(gSaleContractManagement.getId());
                materialProductsOut.setContractNumber(gSaleContractManagement.getNumber());

            }
            materialProductsOut.setDeliveryNote(saleShippingApplication.getDeliveryOrderNumber());
            materialProductsOut.setOutReason(saleShippingApplication.getPurposeOut());
            materialProductsOut.setOrderNumber(saleShippingApplication.getOrderNumber());
            materialProductsOut.setShppingId(saleShippingApplication.getId());
            List<MaterialCpBcpItemsInfo> materialCpBcpItemsInfoList = new ArrayList<>();
            List<SalesShippingItems> list = salesShippingItemsService.list(Wrappers.<SalesShippingItems>lambdaQuery().eq(SalesShippingItems::getShippingId, saleShippingApplication.getId()));
            for (SalesShippingItems salesShippingItems : list) {
                MaterialCpBcpItemsInfo materialCpBcpItemsInfo = MaterialCpBcpItemsInfo.builder()
                        .aTypeShelf(salesShippingItems.getLevelRack())
                        .batchNumber(salesShippingItems.getBatchNumber())
                        .executionStandard(salesShippingItems.getExecutionStandard())
                        .itemCode(salesShippingItems.getProductCode())
                        .itemId(salesShippingItems.getProductId())
                        .quantity(salesShippingItems.getQuantity())
                        .specification(salesShippingItems.getSpecification())
                        .itemName(salesShippingItems.getProductName())
                        .grade(salesShippingItems.getGrade())
                        .LotQuantity(salesShippingItems.getQuantity())
                        .build();
                if (StringUtils.equals(saleShippingApplication.getProductType(), Constants.ONE_STR)) {
                    SalesShippingItems wareHouseAndId = baseMapper.getWareHouseAndId(materialCpBcpItemsInfo.getBatchNumber());
                    if (wareHouseAndId != null) {
                        materialCpBcpItemsInfo.setStorageLocationId(wareHouseAndId.getStorageLocation());
                        materialCpBcpItemsInfo.setGrade(wareHouseAndId.getModelGrade());
                        materialCpBcpItemsInfo.setUnit(wareHouseAndId.getUnit());
                        materialCpBcpItemsInfo.setSpecification(wareHouseAndId.getSpecification());
                        if (StringUtils.isNotEmpty(wareHouseAndId.getWarehouseId())) {
                            SalesShippingItems wareHouseName = baseMapper.getWareHouseName(wareHouseAndId.getWarehouseId());
                            materialCpBcpItemsInfo.setWarehouseId(wareHouseAndId.getWarehouseId());
                            materialCpBcpItemsInfo.setWarehouseName(wareHouseName.getWarehouseName());
                        }
                    }
                } else {
                    SalesShippingItems wareHouseAndId = baseMapper.getWareHouseAndId(materialCpBcpItemsInfo.getBatchNumber());
                    if (wareHouseAndId != null) {
                        materialCpBcpItemsInfo.setStorageLocationId(wareHouseAndId.getStorageLocation());
                        materialCpBcpItemsInfo.setGrade(wareHouseAndId.getGrade());
                        materialCpBcpItemsInfo.setUnit(wareHouseAndId.getUnit());
                        materialCpBcpItemsInfo.setSpecification(wareHouseAndId.getSpecification());
                        if (StringUtils.isNotEmpty(wareHouseAndId.getWarehouseId())) {
                            SalesShippingItems wareHouseName = baseMapper.getWareHouseName(wareHouseAndId.getWarehouseId());
                            materialCpBcpItemsInfo.setWarehouseId(wareHouseAndId.getWarehouseId());
                            materialCpBcpItemsInfo.setWarehouseName(wareHouseName.getWarehouseName());
                        }
                    }
                }
                materialCpBcpItemsInfoList.add(materialCpBcpItemsInfo);
                if (salesShippingItems.getQuantity() != null) {
                    totalQuality = totalQuality.add(salesShippingItems.getQuantity());
                }
            }
            materialProductsOut.setMaterialCpBcpItemsList(materialCpBcpItemsInfoList);
            if (StringUtils.isNotEmpty(saleShippingApplication.getOrderingSettlementCustomer())) {
                GSaleCustomerManagement gSaleCustomerManagement = saleCustomerManagementMapper.selectById(saleShippingApplication.getOrderingSettlementCustomer());
                if (gSaleCustomerManagement != null) {
                    materialProductsOut.setCustomerId(gSaleCustomerManagement.getId());
                    materialProductsOut.setCustomerName(gSaleCustomerManagement.getCustomerName());
                }

            }

            if (StringUtils.isNotEmpty(saleShippingApplication.getOrderingSettlementCustomer())) {
                GSaleCustomerManagement gSaleCustomerManagement = saleCustomerManagementMapper.selectById(saleShippingApplication.getOrderingSettlementCustomer());
                if (gSaleCustomerManagement != null) {
                    materialProductsOut.setCustomerCode(gSaleCustomerManagement.getCustomerName());
                    materialProductsOut.setCustomerName(gSaleCustomerManagement.getCustomerName());
                }
            }
            materialProductsOut.setOrderNumber(saleShippingApplication.getOrderNumber());
//                materialProductsOut.setATypeShelf(salesShippingItems.getLevelRack());
            materialProductsOut.setReturnId(saleShippingApplication.getId());
            materialProductsOut.setType(Constants.SIX_STR);
            materialProductsOut.setOutReason("main_pl_purpose_xsck");
            if (StringUtils.equals(saleShippingApplication.getProductType(), Constants.ONE_STR)) {
                materialProductsOut.setMenuId(SaleMenuIdCode.MENU_ID_CPK_OUT.getMsg());
                materialProductsOut.setItemType(Constants.CP_NAME);
                materialProductsOut.setWarehouseName(Constants.CP_WARE_HOUSE);
                materialApi.addMaterialCpOutBound(materialProductsOut);
            } else {
                materialProductsOut.setMenuId(SaleMenuIdCode.MENU_ID_BCPK_OUT.getMsg());
                materialApi.addMaterialBcpOutBound(materialProductsOut);
                materialProductsOut.setWarehouseName(Constants.BCP_WARE_HOUSE);
                materialProductsOut.setItemType(Constants.BCP_NAME);
            }
            if (saleShippingApplication.getShippedQuantity() != null) {
                totalQuality = totalQuality.add(saleShippingApplication.getShippedQuantity());
            }

            if (totalQuality.compareTo(saleShippingApplication.getTotalQuantity()) >= 0) {
                saleShippingApplication1.setShappingStatus(Constants.TWO_STR);
            }

            if (totalQuality.compareTo(saleShippingApplication.getTotalQuantity()) < 0) {
                saleShippingApplication1.setShappingStatus(Constants.ONE_STR);
            }
//            saleShippingApplication1.setShippedQuantity(totalQuality);
            baseMapper.updateById(saleShippingApplication1);
        }
    }

    @Override
    public SaleShippingApplication getOneSaleShippingApplication(String id) {
        SaleShippingApplication saleShippingApplication = baseMapper.selectById(id);
        List<SalesShippingItems> list = salesShippingItemsService.list(Wrappers.<SalesShippingItems>lambdaQuery().eq(SalesShippingItems::getShippingId, id));
        ResultBody<List<String>> fileIdsByBusinessId = fileApi.getFileIdsByBusinessId(id);
        if (fileIdsByBusinessId != null) {
            saleShippingApplication.setCoaFileList(fileIdsByBusinessId.getData());
        }
        saleShippingApplication.setSalesShippingItemsList(list);
        return saleShippingApplication;
    }

    @Override
    public List<ProductInfo> getProductList(String id) {
        List<ProductInfo> productInfoList = new ArrayList<>();
        SaleShippingApplication saleShippingApplication = baseMapper.selectById(id);
        ResultBody<ProductInfo> productById = portalApi.getProductById(saleShippingApplication.getProductId());
        if (productById != null) {
            productInfoList.add(productById.getData());
        }
        return productInfoList;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateQs(String id) {
        SaleShippingApplication saleShippingApplication = baseMapper.selectById(id);
        List<SaleShippingApplication> saleShippingApplications = baseMapper.selectList(Wrappers.<SaleShippingApplication>lambdaQuery().eq(SaleShippingApplication::getOrderNumber, saleShippingApplication.getOrderNumber()));
        for (SaleShippingApplication saleShippingApplication1 : saleShippingApplications) {
            if (saleShippingApplication1.getShappingStatus().equals(Constants.ONE_STR)) {
                throw new ServiceException(SaleErrorCode.ORDER_NO_SHIPPING.getCode(), SaleErrorCode.ORDER_NO_SHIPPING.getMsg());
            }
            saleShippingApplication1.setShappingStatus(Constants.THREE_STR);
            baseMapper.updateById(saleShippingApplication1);
        }
    }

    /**
     * 销售业绩
     *
     * @param saleStatisticsManReq
     * @return
     */
    @Override
    public List<StatisticOrderDTO> getStatisticOrderDTOList(GSaleStatisticsManReq saleStatisticsManReq) {
        //销售额计算
        if (Constants.ONE_STR.equals(saleStatisticsManReq.getSaleType())) {
            if (StringUtils.equals(saleStatisticsManReq.getShowType(), Constants.ONE_STR)) {
                List<StatisticOrderDTO> statisticOrderDTOByYear = baseMapper.getStatisticOrderDTOByYear(saleStatisticsManReq);
                return statisticOrderDTOByYear;
            }
            if (StringUtils.equals(saleStatisticsManReq.getShowType(), Constants.TWO_STR)) {
                List<StatisticOrderDTO> statisticOrderDTOByYear = baseMapper.getStatisticOrderDTOByMonth(saleStatisticsManReq);
                return statisticOrderDTOByYear;
            }
            if (StringUtils.equals(saleStatisticsManReq.getShowType(), Constants.THREE_STR)) {
                List<StatisticOrderDTO> statisticOrderDTOByYear = baseMapper.getStatisticOrderDTOByJD(saleStatisticsManReq);
                return statisticOrderDTOByYear;
            }
        } else {
            if (StringUtils.equals(saleStatisticsManReq.getShowType(), Constants.ONE_STR)) {
                List<StatisticOrderDTO> statisticOrderDTOByYear = baseMapper.getStatisticAllAmountOrderDTOByYear(saleStatisticsManReq);
                List<StatisticOrderDTO> statisticDFHAmountOrderDTOByYear = baseMapper.getStatisticDFHAmountOrderDTOByYear(saleStatisticsManReq);
                Map<String, BigDecimal> DFHMap = new HashMap<>();
                for (StatisticOrderDTO statisticOrderDTO : statisticDFHAmountOrderDTOByYear) {
                    DFHMap.put(statisticOrderDTO.getDateTime(), statisticOrderDTO.getPlanOrderAmount());
                }

                List<StatisticOrderDTO> statisticYFHAmountOrderDTOByYear = baseMapper.getStatisticYFHAmountOrderDTOByYear(saleStatisticsManReq);
                Map<String, BigDecimal> YFHMap = new HashMap<>();
                for (StatisticOrderDTO statisticOrderDTO : statisticYFHAmountOrderDTOByYear) {
                    YFHMap.put(statisticOrderDTO.getDateTime(), statisticOrderDTO.getPlanOrderAmount());
                }
                for (StatisticOrderDTO statisticOrderDTO : statisticOrderDTOByYear) {
                    if (DFHMap != null) {
                        if (DFHMap.get(statisticOrderDTO.getDateTime()) != null) {
                            statisticOrderDTO.setOverOrderAmount(DFHMap.get(statisticOrderDTO.getDateTime()));
                        }
                    }
                    if (YFHMap != null) {
                        if (YFHMap.get(statisticOrderDTO.getDateTime()) != null) {
                            statisticOrderDTO.setPlanOrderAmount(YFHMap.get(statisticOrderDTO.getDateTime()));
                        }
                    }
                }
                return statisticOrderDTOByYear;
            }
            if (StringUtils.equals(saleStatisticsManReq.getShowType(), Constants.TWO_STR)) {
                List<StatisticOrderDTO> statisticOrderDTOByMonth = baseMapper.getStatisticAllAmountOrderDTOByMonth(saleStatisticsManReq);
                List<StatisticOrderDTO> statisticDFHAmountOrderDTOByMonth = baseMapper.getStatisticDFHAmountOrderDTOByMonth(saleStatisticsManReq);
                Map<String, BigDecimal> DFHMap = new HashMap<>();
                for (StatisticOrderDTO statisticOrderDTO : statisticDFHAmountOrderDTOByMonth) {
                    DFHMap.put(statisticOrderDTO.getDateTime(), statisticOrderDTO.getPlanOrderAmount());
                }
                List<StatisticOrderDTO> statisticYFHAmountOrderDTOByMonth = baseMapper.getStatisticYFHAmountOrderDTOByMonth(saleStatisticsManReq);
                Map<String, BigDecimal> YFHMap = new HashMap<>();
                for (StatisticOrderDTO statisticOrderDTO : statisticYFHAmountOrderDTOByMonth) {
                    YFHMap.put(statisticOrderDTO.getDateTime(), statisticOrderDTO.getPlanOrderAmount());
                }
                for (StatisticOrderDTO statisticOrderDTO : statisticOrderDTOByMonth) {
                    if (DFHMap != null) {
                        if (DFHMap.get(statisticOrderDTO.getDateTime()) != null) {
                            statisticOrderDTO.setOverOrderAmount(DFHMap.get(statisticOrderDTO.getDateTime()));
                        }
                    }
                    if (YFHMap != null) {
                        if (YFHMap.get(statisticOrderDTO.getDateTime()) != null) {
                            statisticOrderDTO.setPlanOrderAmount(YFHMap.get(statisticOrderDTO.getDateTime()));
                        }
                    }
                }
                return statisticOrderDTOByMonth;
            }
            if (StringUtils.equals(saleStatisticsManReq.getShowType(), Constants.THREE_STR)) {
                List<StatisticOrderDTO> statisticOrderDTOByMonth = baseMapper.getStatisticAllAmountOrderDTOByJD(saleStatisticsManReq);
                List<StatisticOrderDTO> statisticDFHAmountOrderDTOByMonth = baseMapper.getStatisticDFHAmountOrderDTOByJD(saleStatisticsManReq);
                Map<String, BigDecimal> DFHMap = new HashMap<>();
                for (StatisticOrderDTO statisticOrderDTO : statisticDFHAmountOrderDTOByMonth) {
                    DFHMap.put(statisticOrderDTO.getDateTime(), statisticOrderDTO.getPlanOrderAmount());
                }
                List<StatisticOrderDTO> statisticYFHAmountOrderDTOByMonth = baseMapper.getStatisticYFHAmountOrderDTOByJD(saleStatisticsManReq);
                Map<String, BigDecimal> YFHMap = new HashMap<>();
                for (StatisticOrderDTO statisticOrderDTO : statisticYFHAmountOrderDTOByMonth) {
                    YFHMap.put(statisticOrderDTO.getDateTime(), statisticOrderDTO.getPlanOrderAmount());
                }
                for (StatisticOrderDTO statisticOrderDTO : statisticOrderDTOByMonth) {
                    if (DFHMap != null) {
                        if (DFHMap.get(statisticOrderDTO.getDateTime()) != null) {
                            statisticOrderDTO.setOverOrderAmount(DFHMap.get(statisticOrderDTO.getDateTime()));
                        }
                    }
                    if (YFHMap != null) {
                        if (YFHMap.get(statisticOrderDTO.getDateTime()) != null) {
                            statisticOrderDTO.setPlanOrderAmount(YFHMap.get(statisticOrderDTO.getDateTime()));
                        }
                    }
                }
                return statisticOrderDTOByMonth;
            }
        }
        return null;
    }


    /**
     * 收款进度
     *
     * @param salePayProgressReq
     * @return
     */
    @Override
    public PayProgressDTO paymentProgress(SalePayProgressReq salePayProgressReq) {
        PayProgressDTO payProgressDTO = new PayProgressDTO();
        PayProgressDTO.Pie pie = new PayProgressDTO.Pie();
        BigDecimal noPay = baseMapper.getNoPay(salePayProgressReq);
        BigDecimal yesPay = baseMapper.getYesPay(salePayProgressReq);
        pie.setOverOrderAmount(yesPay);
        pie.setPlanOrderAmount(noPay);
        payProgressDTO.setPie(pie);
        if (StringUtils.equals(salePayProgressReq.getShowType(), Constants.ONE_STR)) {
            List<SaleLineAmountDTO> lineAmountBYYearList = baseMapper.getLineAmountBYYearList(salePayProgressReq);
            payProgressDTO.setLineAmountList(lineAmountBYYearList);
        }
        if (StringUtils.equals(salePayProgressReq.getShowType(), Constants.TWO_STR)) {
            List<SaleLineAmountDTO> lineAmountBYYearList = baseMapper.getLineAmountBYMonthList(salePayProgressReq);
            payProgressDTO.setLineAmountList(lineAmountBYYearList);
        }
        if (StringUtils.equals(salePayProgressReq.getShowType(), Constants.THREE_STR)) {
            List<SaleLineAmountDTO> lineAmountBYYearList = baseMapper.getLineAmountBYJDList(salePayProgressReq);
            payProgressDTO.setLineAmountList(lineAmountBYYearList);
        }
        return payProgressDTO;
    }


    /**
     * 异议处理
     *
     * @param salePayProgressReq
     * @return
     */
    @Override
    public List<GSaleDisputeLineDTO> getGSaleDisputeLineDTOList(SalePayProgressReq salePayProgressReq) {
        List<GSaleDisputeLineDTO> gSaleDisputeLineDTOList = new ArrayList<>();
        if (StringUtils.equals(salePayProgressReq.getShowType(), Constants.ONE_STR)) {
            gSaleDisputeLineDTOList = baseMapper.getGSaleDisputeLineDTOList(salePayProgressReq);
        }
        if (StringUtils.equals(salePayProgressReq.getShowType(), Constants.TWO_STR)) {
            gSaleDisputeLineDTOList = baseMapper.getGSaleDisputeLineMonthDTOList(salePayProgressReq);
        }
        if (StringUtils.equals(salePayProgressReq.getShowType(), Constants.THREE_STR)) {
            gSaleDisputeLineDTOList = baseMapper.getGSaleDisputeLineJDDTOList(salePayProgressReq);
        }
        return gSaleDisputeLineDTOList;
    }

    @RedissonLock(key = MATERIAL_IN_WAREHOUSE_NUMBER, prefixKey = "lock_")
    public String getMaterialOUTNumber() {
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern(CommonConstant.DATE_FORMAT_UN_SEPARATE));
        date = "OUT".concat(date);
        String code = "";

        Serializable number = rediservice.get(RedisKey.MATERIAL_OUT_WAREHOUSE_NUMBER);
        if (number == null || StringUtils.isBlank(number.toString())) {
            ResultBody<String> resultBody = portalApi.getValueByCode(SALE_OUT_NUMBER);
            if (resultBody != null && StringUtils.isNotBlank(resultBody.getData())) {
                number = resultBody.getData();
            }
        }
        if (number != null && StringUtils.isNotBlank(number.toString()) && number.toString().length() > 11) {
            String sequenceStr = number.toString().substring(11);
            int sequenceInt = Integer.parseInt(sequenceStr);
            sequenceInt = sequenceInt + 1;
            String newSequence = String.valueOf(sequenceInt);
            if (newSequence.length() == CommonConstant.FIVE_INT) {
                code = date.concat("0001");
            } else {
                code = date.concat(String.format("%04d", sequenceInt)); // 格式化数字为4位，不足部分用0填充
            }
        } else {
            code = date.concat("0001");
        }
        rediservice.set(RedisKey.MATERIAL_OUT_WAREHOUSE_NUMBER, code);
        DictInfo info = new DictInfo();
        info.setCsdm(RedisKey.MATERIAL_OUT_WAREHOUSE_NUMBER);
        info.setCsmc(code);
        portalApi.updateValueByCode(info);
        return code;
    }

    @Override
    public List<SalesShippingItems> getProductByOrderNumber(String number) {
        List<SaleShippingApplication> saleShippingApplications = baseMapper.selectList(Wrappers.<SaleShippingApplication>lambdaQuery().eq(SaleShippingApplication::getOrderNumber, number));
        List<SalesShippingItems> salesShippingItemsByNumber = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(saleShippingApplications)) {
            List<String> collect = saleShippingApplications.stream().map(SaleShippingApplication::getId).collect(Collectors.toList());
            salesShippingItemsByNumber = baseMapper.getSalesShippingItemsByNumber(collect);
            return salesShippingItemsByNumber;
        }
        return salesShippingItemsByNumber;
    }

    @Override
    public List<SaleShippingApplication> getShippingNumber(String number) {
        List<SaleShippingApplication> saleShippingApplications = baseMapper.selectList(Wrappers.<SaleShippingApplication>lambdaQuery().select(SaleShippingApplication::getDeliveryOrderNumber, SaleShippingApplication::getId).eq(SaleShippingApplication::getApproveStatus, Constants.TWO_STR)
                .eq(SaleShippingApplication::getOrderNumber, number)
                .isNotNull(SaleShippingApplication::getDeliveryOrderNumber)
        );
        return saleShippingApplications;
    }

    @Override
    public List<SalesShippingItems> getATypeList(SalesShippingItems salesShippingItems) {
        List<SaleShippingApplication> saleShippingApplications = baseMapper.selectList(Wrappers.<SaleShippingApplication>lambdaQuery().eq(SaleShippingApplication::getOrderNumber, salesShippingItems.getNumber()));
        List<SalesShippingItems> salesShippingItemsByNumber = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(saleShippingApplications)) {
            List<String> collect = saleShippingApplications.stream().map(SaleShippingApplication::getId).collect(Collectors.toList());
            salesShippingItemsByNumber = baseMapper.getATypeList(salesShippingItems, collect);
            return salesShippingItemsByNumber;
        }
        return salesShippingItemsByNumber;
    }


    @Override
    public void saleShippingApplicationById(SaleShippingApplication saleShippingApplication) {
        SaleShippingApplication saleShippingApplication1 = baseMapper.selectById(saleShippingApplication.getId());
        if (saleShippingApplication1.getPendingShipment().compareTo(saleShippingApplication.getShippedQuantity()) <= 0) {
            saleShippingApplication1.setPendingShipment(BigDecimal.ZERO);
        } else {
            BigDecimal subtract = saleShippingApplication1.getPendingShipment().subtract(saleShippingApplication.getShippedQuantity());
            saleShippingApplication1.setPendingShipment(subtract);
        }
        saleShippingApplication1.setShippedQuantity(saleShippingApplication.getShippedQuantity());
        baseMapper.updateById(saleShippingApplication1);
    }


    @Override
    public void updateSaleQualityById(String id) {
        SaleShippingApplication saleShippingApplication = baseMapper.selectById(id);
//        BigDecimal pendingShipment = saleShippingApplication.getPendingShipment();
//        BigDecimal totalQuantity = saleShippingApplication.getTotalQuantity();
//        if (pendingShipment != null && totalQuantity != null) {
//            BigDecimal add = totalQuantity.add(pendingShipment);
//            saleShippingApplication.setTotalQuantity(add);
//        }
        saleShippingApplication.setShappingStatus(Constants.ONE_STR);
        saleShippingApplication.setPendingShipment(BigDecimal.ZERO);
        baseMapper.updateById(saleShippingApplication);
    }

}
